﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel.Channels;
using EbayQueryExpertLib.EbayFinding;
using System.ServiceModel;
using EbayQueryExpertLib.Entities;

namespace EbayQueryExpertLib
{
    public static class EbayEndPoint
    {
        public static FindItemsAdvancedResponse AdvancedSearch(int page, int perPage, AbstractSearchQuery query)
        {

            HttpRequestMessageProperty httpRequestProperty = new HttpRequestMessageProperty();
            httpRequestProperty.Headers.Add("X-EBAY-SOA-SECURITY-APPNAME", "EricMass-d56b-4d34-bf83-8f54ca540f97");
            httpRequestProperty.Headers.Add("X-EBAY-SOA-OPERATION-NAME", "findItemsAdvanced");
            httpRequestProperty.Headers.Add("X-EBAY-SOA-GLOBAL-ID", "EBAY-US");
            using (FindingServicePortTypeClient client = new FindingServicePortTypeClient())
            {
                MessageHeader header = MessageHeader.CreateHeader("CustomHeader", "", "");
                using (OperationContextScope scope = new OperationContextScope(client.InnerChannel))
                {
                    OperationContext.Current.OutgoingMessageHeaders.Add(header);
                    OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpRequestProperty;

                    FindItemsAdvancedRequest request = new FindItemsAdvancedRequest();
                    PaginationInput pi = new PaginationInput();
                    pi.entriesPerPage = perPage;
                    pi.entriesPerPageSpecified = true;
                    pi.pageNumber = page;
                    pi.pageNumberSpecified = true;
                    request.paginationInput = pi;
                    request.keywords = query.Keywords;
                    request.categoryId = query.CategoriesArray;
                    request.itemFilter = new ItemFilter[query.Filters.Count];
                    ItemFilterType[] keys = new ItemFilterType[query.Filters.Count];
                    query.Filters.Keys.CopyTo(keys, 0);
                    for (int i = 0; i < query.Filters.Count; ++i)
                    {
                        ItemFilter ifr = new ItemFilter();
                        ifr.name = keys[i];
                        if (keys[i] == ItemFilterType.LocatedIn && query.Filters[keys[i]] == "ANY")
                            ifr.value = new string[] { "WorldWide", "US", "CA", "ZA", "AU", "TH", "MX", "RU", "KP", "KR", "GB", "BR", "ID", "IN", "ES", "IT", "DE", "FR", "JP", "CN" };
                        else
                            ifr.value = new string[] { query.Filters[keys[i]] };
                        request.itemFilter[i] = ifr;
                    }
                    return client.findItemsAdvanced(request);
                }
            }
        }
    }
}
